<template>
  <div class="onePageTable">
  <div class="commonTablePanel openatc-role">
    <div class="common-table-header">
    <div class="common-table-title-container">
      <div class="common-table-title">{{$t('auth.route.role')}}</div>
    </div>
    <div class="filter-container">
      <el-form>
        <el-form-item>
          <el-button
            type="primary"
            icon="plus"
            :disabled="!role_edit"
            @click="showCreate"
          >
            {{$t('auth.common.add')}}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
    <div class="atc-table">
      <el-table
        :data="list"
        size="mini"
        v-loading.body="listLoading"
        element-loading-text="load..."
        fit
        highlight-current-row
        style="width: 100%;font-size: 14px;"
        :max-height="tableHeight"
        id="footerBtn"
      >
        <el-table-column
          header-align="center"
          label="No"
          width="50"
        >
          <template slot-scope="scope">
            <span v-text="getIndex(scope.$index)"> </span>
          </template>
        </el-table-column>
        <el-table-column
          header-align="center"
          :label="$t('auth.common.name')"
          prop="name"
        ></el-table-column>
        <el-table-column
          header-align="center"
          :label="$t('auth.common.description')"
          prop="description"
        ></el-table-column>
        <el-table-column
          header-align="center"
          :label="$t('auth.common.operations')"
        >
          <template slot-scope="scope">
            <div style="display:flex;justify-content:center">
              <el-button
                type="text"
                :disabled="!role_edit"
                @click="showUpdate(scope.$index)"
              >
                {{$t('auth.common.update')}}
              </el-button>
              <el-button
                type="text"
                :disabled="!role_edit"
                @click="removeRole(scope.$index)"
              >
                {{$t('auth.common.delete')}}
              </el-button>
              <el-button
                type="text"
                :disabled="!permission_edit"
                @click="relatePermission(scope.$index)"
              >
                {{$t('auth.role.relPermissions')}}
              </el-button>
              <!-- <el-button
                type="text"
                :disabled="!user_edit"
                @click="relateUser(scope.$index)"
              >
                {{$t('auth.role.relateusr')}}
              </el-button> -->
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--以下为dialog的组件-->
    <edit
      ref="editChild"
      :dialogFormVisible="editVisible"
      :dialogTittle="dialogStatesList[dialogStatus]"
      @onConfirm="onEditConfirm"
    ></edit>
    <users
      ref="userChild"
      :allUser="allUser"
    ></users>
    <permissions
      ref="permissionChild"
      :treeData="treeData"
    ></permissions>
  </div>
</div>
</template>
<script>
/* eslint-disable */
import {
  GetRoleList,
  AddRole,
  GetRoleById,
  UpdateRole,
  DeleteRole,
  GetUserById,
  UpdateUser
} from "../../api/role";
import {
  GetPermissionList,
  GetPermissionById,
  AddPermission,
  UpdatePermission,
  DeletePermission
} from "../../api/permission";
import { elTreeModel } from "../../model/tree/permissionTree";
import { GetUsrInfoList } from "../../api/user";
import { CheckPermissions } from "../../api/base";
import edit from "./RoleDialog/edit";
import users from "./RoleDialog/users";
import permissions from "./RoleDialog/permissions";
import { getMessageByCode } from '../../utils/responseMessage'
export default {
  name: 'role',
  components: { edit, users, permissions },

  data () {
    return {
      list: [], //表格的数据
      allPermission: [],
      listLoading: false, //数据加载等待动画
      dialogStatesList: [this.$t('auth.role.addrole'), this.$t('auth.role.updaterole')],
      dialogStatus: 0,
      treeData: this.treeData,
      allUser: [],
      user_edit: false,
      role_edit: true,
      permission_edit: true,
      editVisible: false,
      editObjectList: [],
      tableHeight: 760,
      screenHeight: window.innerHeight // 屏幕高度
    };
  },
  mounted: function() {
        var _this = this;
        _this.$nextTick(function() {
           //window.innerHeight:浏览器的可用高度
          //this.$refs.table.$el.offsetTop：表格距离浏览器的高度
          //后面的50：根据需求空出的高度，自行调整
            _this.tableHeight =
                window.innerHeight -
                document.querySelector("#footerBtn").offsetTop -
                60;
                console.log('tableHeight:' + _this.tableHeight)
            window.onresize = function() {
                // 定义窗口大小变更通知事件
                _this.screenHeight = window.innerHeight; //窗口高度
            };
        });
    },
    watch: {
        screenHeight: function() {
            //监听屏幕高度变化
            this.tableHeight =
                window.innerHeight -
                document.querySelector("#footerBtn").offsetTop -
                50;
        }
    },
  created () {
    this.getList();
  },
  // computed: {
  //   tableHeight () {
  //     return this.isIE ? this.tableHeightforIE : this.tableHeightforChrome
  //   }
  // },
  methods: {
    getAllPermisson () {
      //查询所有权限
      GetPermissionList().then(data => {
        if (data.data.code === '401') { // 判断用户是否在其他地方被踢出
          window.location.reload()
          return
        }
        if (data.data.success !== true) {
          this.$message.error(getMessageByCode(data.data.code, this.$i18n.locale))
          return
        }
        this.allPermission = data.data.data
        let _this = this
        this.allPermission = this.allPermission.map(item => {
          let code = 'auth.permission.' + item.permission_code
          let description = _this.$t(code)
          item.description = description
          return item
        })
        this.treeData = elTreeModel.CreateTreeByPath(
          this.allPermission
        );
      });
    },
    getList () {
      //查询列表
      this.listLoading = true;
      GetRoleList().then(data => {
        if (data.data.code === '401') { // 判断用户是否在其他地方被踢出
          window.location.reload()
          return
        }
        if (data.data.success !== true) {
          this.$message.error(getMessageByCode(data.data.code, this.$i18n.locale))
          return
        }
        this.listLoading = false;
        this.list = data.data.data
      });
      // this.getPermission();
    },
    getIndex ($index) {
      //表格序号
      return $index + 1;
    },
    showCreate () {
      //显示新增对话框
      this.dialogStatus = 0;

      let editObjectList = [
        {
          key: 'name',
          label: 'auth.common.name',
          type: 'text',
          keyword: true,
        },
        {
          key: 'description',
          label: 'auth.common.description',
          type: 'text',
          keyword: false,
        }
      ]
      this.$refs.editChild.InitDialog(editObjectList);
      this.$refs.editChild.show(true)
    },
    showUpdate (index) {
      this.tempRole = this.list[index]
      this.dialogStatus = 1
      let editObjectList = [
        {
          key: 'name',
          label: 'auth.common.name',
          type: 'text',
          keyword: true,
          default: this.tempRole.name,
        },
        {
          key: 'description',
          label: 'auth.common.description',
          type: 'text',
          keyword: false,
          default: this.tempRole.description,
        }
      ]
      this.$refs.editChild.InitDialog(editObjectList);
      this.$refs.editChild.show(true)
    },
    onEditConfirm (valuemap) {
      this.dialogStatus === 0 ? this.createRole(valuemap.get('name'), valuemap.get('description')) :
        this.updateRole(valuemap.get('name'), valuemap.get('description'))
    },
    relatePermission ($index) {
      this.getAllPermisson();
      let role = this.list[$index];
      let permissionChild = this.$refs.permissionChild;
      permissionChild.onPermissionsClick(role);
    },
    relateUser ($index) {
      //查询当前角色有哪些用户
      this.getAllUser();
      let role = this.list[$index];
      let userChild = this.$refs.userChild;
      userChild.onUserClick(role);
    },

    removeRole ($index) {
      let _vue = this;
      this.$confirm(this.$t('auth.role.deletecontain'), this.$t('auth.common.alarm'), {
        confirmButtonText: this.$t('auth.common.confirm'),
        showCancelButton: false,
        type: "warning"
      })
        .then(() => {
          let role = _vue.list[$index];

          DeleteRole(role.id).then(data => {
            if (data.data.code === '401') { // 判断用户是否在其他地方被踢出
              window.location.reload()
              return
            }
            if (data.data.success !== true) {
              this.$message.error(getMessageByCode(data.data.code, this.$i18n.locale))
              return
            }
            let msg = this.$t('auth.common.deletesucess');
            this.$message({
              message: msg,
              type: "success",
              duration: 1 * 1000,
              onClose: () => {
                _vue.getList();
              }
            });
            //_vue.getList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: this.$t('auth.common.deletecancel')
          });
        });
    },
    getAllUser () {
      this.listLoading = true;
      GetUsrInfoList(0, 10000).then(data => {
        if (data.data.code === '401') { // 判断用户是否在其他地方被踢出
          window.location.reload()
          return
        }
        if (data.data.success !== true) {
          this.$message.error(getMessageByCode(data.data.code, this.$i18n.locale))
          return
        }
        this.listLoading = false;
        this.allUser = data.data.data.list;
      });
    },
    getPermission () {
      this.listLoading = true;
      let permissions = [
        "openatc:auth:user:modify",
        "openatc:auth:role:modify",
        "openatc:auth:permission:modify"
      ];
      CheckPermissions(permissions).then(data => {
        if (data.data.code === '401') { // 判断用户是否在其他地方被踢出
          window.location.reload()
          return
        }
        if (data.data.success !== true) {
          this.$message.error(getMessageByCode(data.data.code, this.$i18n.locale))
          return
        }
        this.listLoading = false;
        let list = data.data.data;
        for (let per of data.data.data) {
          if (per.permission === "openatc:auth:user:modify") {
            this.user_edit = per.auth;
          } else if (per.permission === "openatc:auth:role:modify") {
            this.role_edit = per.auth;
          } else {
            this.permission_edit = per.auth;
          }
        }
      });
    },
    createRole (name, description) {
      if (name === "") {
        this.$message.error(this.$t('auth.role.nullerror'));
        return;
      }
      for (let role of this.list) {
        if (name === role.name) {
          this.$message.error(this.$t('auth.role.repeatederror'));
          return;
        }
      }
      AddRole(name, description).then(
        data => {
          if (data.data.code === '401') { // 判断用户是否在其他地方被踢出
            window.location.reload()
            return
          }
          if (data.data.success !== true) {
            this.$message.error(getMessageByCode(data.data.code, this.$i18n.locale))
            return
          }
          let msg = this.$t('auth.common.addsucess')
          this.$refs.editChild.show(false)
          this.$message({
          message: msg,
          type: "success",
          duration: 1 * 1000,
          onClose: () => {
            this.getList()
          }
        });
        }
      );
    },
    updateRole (name, description) {
      let role = this.tempRole
      if (name === "") {
        this.$message.error(this.$t('auth.role.nullerror'));
        return;
      }
      if (
        name === role.name &&
        description === role.description
      ) {
        this.$message.error(this.$t('auth.role.nochangeserror'));
        return;
      }
      UpdateRole(
        role.id,
        name,
        description
      ).then(data => {
        if (data.data.code === '401') { // 判断用户是否在其他地方被踢出
          window.location.reload()
          return
        }
        if (data.data.success !== true) {
          this.$message.error(getMessageByCode(data.data.code, this.$i18n.locale))
          return
        }
        let msg = this.$t('auth.common.updatesucess');
        this.$refs.editChild.show(false)
        this.$message({
          message: msg,
          type: "success",
          duration: 1 * 1000,
          onClose: () => {
            this.getList()
          }
        });
      });
    }
  }
};
</script>
<style scoped>
.requiredPerm {
  color: #ff0e13;
}
</style>
